class UIRenderer {
    constructor(taskManager) {
        this.taskManager = taskManager;
    }

    updateStats() {
        const filteredTodos = this.taskManager.getFilteredTodos();
        const pendingTodos = filteredTodos.filter(t => !t.completed);
        const completedTodos = filteredTodos.filter(t => t.completed);

        const estimatedTime = pendingTodos.reduce((sum, todo) => sum + (todo.estimatedTime || 25), 0);
        const completedTime = completedTodos.reduce((sum, todo) => sum + (todo.estimatedTime || 25), 0);

        const statCards = document.querySelectorAll('.stat-card');
        if (statCards.length >= 4) {
            statCards[0].querySelector('.stat-number').textContent = estimatedTime;
            statCards[1].querySelector('.stat-number').textContent = pendingTodos.length;
            statCards[2].querySelector('.stat-number').textContent = completedTime;
            statCards[3].querySelector('.stat-number').textContent = completedTodos.length;
        }
    }

    // 新增：渲染优先级标识
    renderPriority(priority) {
        const priorityConfig = {
            'high': { icon: '🔴', text: '高', color: '#ff4757' },
            'medium': { icon: '🟡', text: '中', color: '#ffa502' },
            'low': { icon: '🟢', text: '低', color: '#2ed573' }
        };

        const config = priorityConfig[priority] || priorityConfig['medium'];

        return `
            <div class="task-priority priority-${priority}">
                <span class="priority-icon">${config.icon}</span>
                <span class="priority-text">${config.text}优先级</span>
            </div>
        `;
    }

    // 新增：设置优先级按钮事件
    setupPriorityButtons() {
        const priorityButtons = document.querySelectorAll('.priority-btn');
        priorityButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                const taskId = e.currentTarget.dataset.taskId;
                this.showPriorityMenu(taskId, e.currentTarget);
            });
        });
    }

    // 新增：显示优先级菜单
    showPriorityMenu(taskId, button) {
        // 移除现有的优先级菜单
        const existingMenu = document.querySelector('.priority-menu');
        if (existingMenu) {
            existingMenu.remove();
        }

        const menu = document.createElement('div');
        menu.className = 'priority-menu';
        menu.innerHTML = `
            <div class="priority-menu-item" data-priority="high">
                <span class="priority-icon">🔴</span>
                <span>高优先级</span>
            </div>
            <div class="priority-menu-item" data-priority="medium">
                <span class="priority-icon">🟡</span>
                <span>中优先级</span>
            </div>
            <div class="priority-menu-item" data-priority="low">
                <span class="priority-icon">🟢</span>
                <span>低优先级</span>
            </div>
        `;

        // 定位菜单
        const rect = button.getBoundingClientRect();
        menu.style.position = 'fixed';
        menu.style.top = `${rect.bottom + 5}px`;
        menu.style.left = `${rect.left}px`;
        menu.style.zIndex = '1000';

        document.body.appendChild(menu);

        // 添加点击事件
        menu.querySelectorAll('.priority-menu-item').forEach(item => {
            item.addEventListener('click', async (e) => {
                const priority = e.currentTarget.dataset.priority;
                await app.updateTaskPriority(taskId, priority);
                menu.remove();
            });
        });

        // 点击其他地方关闭菜单
        setTimeout(() => {
            document.addEventListener('click', function closeMenu(e) {
                if (!menu.contains(e.target)) {
                    menu.remove();
                    document.removeEventListener('click', closeMenu);
                }
            });
        }, 0);
    }

    // 修改：更新侧边栏显示
    updateCounts() {
        const categories = ['today', 'tomorrow', 'week', 'planned', 'completed', 'tasks', 'high-priority', 'medium-priority', 'low-priority'];

        categories.forEach(category => {
            const navItem = document.querySelector(`[data-category="${category}"]`);
            if (navItem) {
                const count = this.taskManager.getCountForCategory(category);
                const countElement = navItem.querySelector('.count');
                if (countElement) {
                    countElement.textContent = count;
                }
            }
        });

        // 根据设置显示/隐藏优先级分类
        const settings = this.taskManager.getSettings();
        const prioritySection = document.getElementById('prioritySection');
        if (prioritySection) {
            prioritySection.style.display = settings.showPriorityInSidebar ? 'block' : 'none';
        }
    }

    setupTaskContextMenu() {
        const taskItems = document.querySelectorAll('.task-item');
        taskItems.forEach(taskItem => {
            // 将右键事件改为双击事件
            taskItem.addEventListener('dblclick', (e) => {
                e.preventDefault();
                const taskId = taskItem.dataset.id;
                app.showTaskDetail(taskId);
            });
        });
    }

    setupDeleteButtons() {
        // console.log('开始设置删除按钮...');
        
        // 先移除所有旧的事件监听器
        const oldButtons = document.querySelectorAll('.delete-btn');
        // console.log(`找到 ${oldButtons.length} 个旧的删除按钮`);
        
        oldButtons.forEach((button, index) => {
            // console.log(`正在处理第 ${index + 1} 个旧按钮`);
            const newButton = button.cloneNode(true);
            button.parentNode.replaceChild(newButton, button);
        });
        
        // 重新获取按钮并绑定事件
        const deleteButtons = document.querySelectorAll('.delete-btn');
        // console.log(`重新获取到 ${deleteButtons.length} 个删除按钮`);
        
        deleteButtons.forEach((button, index) => {
            // console.log(`正在为第 ${index + 1} 个按钮绑定点击事件`);
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                e.preventDefault();
                const taskId = e.currentTarget.dataset.taskId;
                // console.log(`点击了删除按钮，任务ID: ${taskId}`);
                
                // 修复全局变量访问问题
                if (window.app) {
                    // console.log('通过 window.app 访问全局实例');
                    window.app.confirmDeleteTask(taskId);
                } else if (typeof app !== 'undefined') {
                    // console.log('通过 app 变量访问全局实例');
                    app.confirmDeleteTask(taskId);
                } else {
                    console.error('无法访问全局 app 实例');
                }
            });
        });
        
        // console.log('删除按钮设置完成');
    }

    renderDueDate(dueDateStr) {
        const dueDate = new Date(dueDateStr);
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);

        // 重置时间为当天开始
        today.setHours(0, 0, 0, 0);
        tomorrow.setHours(0, 0, 0, 0);
        dueDate.setHours(0, 0, 0, 0);

        let className = 'task-due-date';
        let text = '';

        if (dueDate.getTime() === today.getTime()) {
            className += ' today';
            text = '今天';
        } else if (dueDate.getTime() === tomorrow.getTime()) {
            className += ' tomorrow';
            text = '明天';
        } else if (dueDate < today) {
            className += ' overdue';
            text = '已过期';
        } else {
            className += ' future';
            text = dueDate.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        }

        return `
            <div class="${className}">
                <i class="fas fa-calendar"></i>
                <span>${text}</span>
            </div>
        `;
    }

    updateCounts() {
        const categories = ['today', 'tomorrow', 'week', 'planned', 'completed', 'tasks'];

        categories.forEach(category => {
            const navItem = document.querySelector(`[data-category="${category}"]`);
            if (navItem) {
                const count = this.taskManager.getCountForCategory(category);
                const countElement = navItem.querySelector('.count');
                if (countElement) {
                    countElement.textContent = count;
                }
            }
        });
    }

    updatePageTitle() {
        const titleMap = {
            'today': '今天',
            'tomorrow': '明天',
            'week': '本周',
            'planned': '已计划',
            'completed': '已完成',
            'tasks': '任务'
        };

        const pageTitle = document.querySelector('.page-title');
        if (pageTitle) {
            pageTitle.textContent = titleMap[this.taskManager.currentCategory] || '任务';
        }
    }

    updateUI() {
        this.updateStats();
        if (this.taskManager.currentView === 'kanban') {
            this.updateKanbanView();
        } else {
            this.updateTasksList();
        }
        this.updateCounts();
        this.updatePageTitle();
    }

    // 新增：更新看板视图
    updateKanbanView() {
        // 隐藏列表视图，显示看板视图
        const tasksList = document.getElementById('tasksList');
        let kanbanContainer = document.getElementById('kanbanContainer');

        tasksList.style.display = 'none';

        if (!kanbanContainer) {
            kanbanContainer = this.createKanbanContainer();
            tasksList.parentNode.insertBefore(kanbanContainer, tasksList.nextSibling);
        }

        kanbanContainer.style.display = 'flex';
        this.renderKanbanTasks();
    }

    // 新增：创建看板容器
    createKanbanContainer() {
        const container = document.createElement('div');
        container.id = 'kanbanContainer';
        container.className = 'kanban-container active';

        container.innerHTML = `
            <div class="kanban-column todo" data-status="todo">
                <div class="kanban-column-header">
                    <div class="kanban-column-title">
                        <i class="fas fa-circle" style="color: #007bff;"></i>
                        待办
                    </div>
                    <span class="kanban-column-count" id="todoCount">0</span>
                </div>
                <div class="kanban-tasks" id="todoTasks"></div>
            </div>
            
            <div class="kanban-column inprogress" data-status="inprogress">
                <div class="kanban-column-header">
                    <div class="kanban-column-title">
                        <i class="fas fa-circle" style="color: #ffc107;"></i>
                        进行中
                    </div>
                    <span class="kanban-column-count" id="inprogressCount">0</span>
                </div>
                <div class="kanban-tasks" id="inprogressTasks"></div>
            </div>
            
            <div class="kanban-column completed" data-status="completed">
                <div class="kanban-column-header">
                    <div class="kanban-column-title">
                        <i class="fas fa-check-circle" style="color: #28a745;"></i>
                        已完成
                    </div>
                    <span class="kanban-column-count" id="completedCount">0</span>
                </div>
                <div class="kanban-tasks" id="completedTasks"></div>
            </div>
        `;

        this.setupKanbanDragAndDrop(container);
        return container;
    }

    // 新增：渲染看板任务
    renderKanbanTasks() {
        const statuses = ['todo', 'inprogress', 'completed'];

        statuses.forEach(status => {
            const tasks = this.taskManager.getTasksByStatus(status);
            const container = document.getElementById(`${status}Tasks`);
            const countElement = document.getElementById(`${status}Count`);

            countElement.textContent = tasks.length;

            if (tasks.length === 0) {
                container.innerHTML = `
                    <div class="kanban-empty">
                        <i class="fas fa-inbox"></i>
                        <div>暂无任务</div>
                    </div>
                `;
            } else {
                container.innerHTML = tasks.map(task => this.renderKanbanTask(task)).join('');
            }
        });

        this.setupKanbanTaskEvents();
    }

    // 新增：渲染单个看板任务
    renderKanbanTask(task) {
        const dueDateHtml = task.dueDate ? this.renderKanbanDueDate(task.dueDate) : '';
        const status = task.status || (task.completed ? 'completed' : 'todo');

        return `
            <div class="kanban-task ${status}" data-id="${task.id}" draggable="true">
                <div class="kanban-task-content">
                    <div class="kanban-task-title">${task.text}</div>
                    <div class="kanban-task-meta">
                        <div class="kanban-task-pomodoros">
                            <i class="fas fa-clock"></i>
                            <span>${task.pomodoros}个番茄</span>
                        </div>
                        ${dueDateHtml}
                    </div>
                </div>
                <div class="kanban-task-actions">
                    <button class="kanban-task-action edit-btn" data-task-id="${task.id}" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="kanban-task-action delete-btn" data-task-id="${task.id}" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }

    // 新增：渲染看板到期时间
    renderKanbanDueDate(dueDateStr) {
        const dueDate = new Date(dueDateStr);
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);

        today.setHours(0, 0, 0, 0);
        tomorrow.setHours(0, 0, 0, 0);
        dueDate.setHours(0, 0, 0, 0);

        let className = 'kanban-task-due';
        let text = '';

        if (dueDate.getTime() === today.getTime()) {
            className += ' today';
            text = '今天';
        } else if (dueDate.getTime() === tomorrow.getTime()) {
            className += ' tomorrow';
            text = '明天';
        } else if (dueDate < today) {
            className += ' overdue';
            text = '已过期';
        } else {
            text = dueDate.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        }

        return `
            <div class="${className}">
                <i class="fas fa-calendar"></i>
                <span>${text}</span>
            </div>
        `;
    }

    // 新增：设置看板拖拽功能
    setupKanbanDragAndDrop(container) {
        const columns = container.querySelectorAll('.kanban-tasks');

        columns.forEach(column => {
            column.addEventListener('dragover', (e) => {
                e.preventDefault();
                column.classList.add('drag-over');
            });

            column.addEventListener('dragleave', (e) => {
                if (!column.contains(e.relatedTarget)) {
                    column.classList.remove('drag-over');
                }
            });

            column.addEventListener('drop', (e) => {
                e.preventDefault();
                column.classList.remove('drag-over');

                const taskId = e.currentTarget.dataset.taskId;
                const newStatus = column.parentElement.dataset.status;

                app.updateTaskStatus(taskId, newStatus);
            });
        });
    }

    // 新增：设置看板任务事件
    setupKanbanTaskEvents() {
        // 拖拽事件
        document.querySelectorAll('.kanban-task').forEach(task => {
            task.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', task.dataset.id);
                task.classList.add('dragging');
            });

            task.addEventListener('dragend', () => {
                task.classList.remove('dragging');
            });

            // 双击编辑
            task.addEventListener('dblclick', (e) => {
                e.preventDefault();
                const taskId = task.dataset.id;
                app.showTaskDetail(taskId);
            });
        });

        // 编辑按钮
        document.querySelectorAll('.kanban-task-action.edit-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const taskId = btn.dataset.taskId;
                app.showTaskDetail(taskId);
            });
        });

        // 删除按钮
        document.querySelectorAll('.kanban-task-action.delete-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const taskId = btn.dataset.taskId;
                app.confirmDeleteTask(taskId);
            });
        });
    }

    // 修改：更新任务列表方法
    updateTasksList() {
        const tasksList = document.getElementById('tasksList');
        const kanbanContainer = document.getElementById('kanbanContainer');

        // 显示列表视图，隐藏看板视图
        tasksList.style.display = 'block';
        if (kanbanContainer) {
            kanbanContainer.style.display = 'none';
        }

        const filteredTodos = this.taskManager.getFilteredTodos();

        if (filteredTodos.length === 0) {
            tasksList.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="fas fa-clipboard-list"></i>
                    </div>
                    <div class="empty-text">暂无任务</div>
                    <div class="empty-subtext">添加一个新任务开始专注工作</div>
                </div>
            `;
            return;
        }
        // 在 renderTasks 方法中修改任务项HTML
        tasksList.innerHTML = filteredTodos.map(todo => {
            const dueDateHtml = todo.dueDate ? this.renderDueDate(todo.dueDate) : '';
            const priorityHtml = this.renderPriority(todo.priority || 'medium');

            return `
                <div class="task-item ${todo.completed ? 'completed' : ''} priority-${todo.priority || 'medium'}" data-id="${todo.id}">
                    <div class="task-checkbox ${todo.completed ? 'completed' : ''}">
                        <input type="checkbox" ${todo.completed ? 'checked' : ''} onchange="app.toggleTask(${todo.id})">
                        <span class="checkmark"></span>
                    </div>
                    <div class="task-content ${todo.completed ? 'completed' : ''}">
                        <div class="task-main-content">
                            <button class="task-action-btn priority-btn priority-${todo.priority || 'medium'}" data-task-id="${todo.id}" title="设置优先级">
                                <i class="fas fa-flag"></i>
                            </button>
                            <div class="task-text">${todo.text}</div>
                        </div>
                        <div class="task-meta">
                            ${todo.pomodoros ? `
                            <div class="task-pomodoros">
                                <i class="fas fa-clock"></i>
                                <span>${todo.pomodoros}个番茄</span>
                            </div>
                            ` : ''}
                            ${dueDateHtml}
                        </div>
                    </div>
                    <div class="task-actions">
                        ${todo.pomodoros ? `
                        <button class="task-action-btn pomodoro-start-btn" data-task-id="${String(todo.id)}" title="开始番茄时钟">
                            <i class="fas fa-play-circle"></i>
                        </button>
                        ` : ''}
                        <button class="task-action-btn delete-btn" data-task-id="${String(todo.id)}" title="删除任务">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `;
        }).join('');

        this.setupDeleteButtons();
        this.setupTaskContextMenu();
        this.setupPomodoroButtons(); // 新增：设置番茄时钟按钮事件
    }

    // 在UIRenderer类中添加新方法
    setupPomodoroButtons() {
        // 先移除所有旧的事件监听器
        const oldButtons = document.querySelectorAll('.pomodoro-start-btn');
        oldButtons.forEach(button => {
            // 克隆节点来移除所有事件监听器
            const newButton = button.cloneNode(true);
            button.parentNode.replaceChild(newButton, button);
        });
        
        // 重新获取按钮并绑定事件
        const pomodoroButtons = document.querySelectorAll('.pomodoro-start-btn');
        pomodoroButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                e.preventDefault();
                const taskId = button.dataset.taskId;
                const task = app.taskManager.todos.find(t => t.id === taskId);
                if (task) {
                    app.pomodoroTimer.startTaskTimer(task);
                }
            });
        });
    }
}

// 删除这行：module.exports = UIRenderer;